package com.app.base.service.core.employees.service.impl;

import com.app.base.config.exception.SaaSException;
import com.app.base.model.vo.UsCoVo;
import com.app.base.service.auth.service.SysUserService;
import com.app.base.service.core.employees.entity.EmpType;
import com.app.base.service.core.employees.mapper.EmpTypeMapper;
import com.app.base.service.core.employees.service.EmpTypeService;
import com.app.base.utlis.result.Result;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 *  服务实现类
 * @author yuhag
 * @since 2022-05-11
 */
@Service
@Slf4j
public class EmpTypeServiceImpl extends ServiceImpl<EmpTypeMapper, EmpType> implements EmpTypeService {

    @Resource
    private SysUserService userService;

    @Override
    public Result saveOrUpdateEmpType(String userId, EmpType type) {
        try{
            if (!StringUtils.isEmpty(type)) {
                type.setModifyBy(userId);
                if (StringUtils.isEmpty(type.getId())) {
                    type.setCreatedBy(userId);
                    type.setCompanyId(userService.getCompanyId(userId));
                    baseMapper.insert(type);
                }else {
                    baseMapper.updateById(type);
                }
            }else {
                throw new SaaSException("表单数据为空");
            }

            return Result.ok(type.getId());
        }catch(Exception e){
            log.error(e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    @Override
    public Result pageEmpList(Long current, Long pageSize) {
        try{
            Page<EmpType> page = new Page<>(current,pageSize);
            baseMapper.selectPage(page,new QueryWrapper<EmpType>().orderByDesc("create_time"));
            return Result.ok(page);
        }catch(Exception e){
            log.error(e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    @Override
    public Result empList(HttpServletRequest request) {
        try{
            UsCoVo userCompanyInfo = userService.getUserCompanyInfo(request);
            List<EmpType> list = baseMapper.selectList(new QueryWrapper<EmpType>()
                    .eq("company_id",userCompanyInfo.getCompanyId()));
            return Result.ok(list);
        }catch(Exception e){
            log.error(e.getMessage());
            return Result.error(e.getMessage());
        }
    }
}
